import AVFoundation
import UIKit

/**
 * iOS原生摄像头管理器
 * 
 * 使用AVFoundation框架提供稳定可靠的摄像头功能
 * 支持iOS 12.0+，兼容性极佳
 */
public class NativeCameraManager: NSObject {
    
    // MARK: - Properties
    
    private var captureSession: AVCaptureSession?
    private var photoOutput: AVCapturePhotoOutput?
    private var videoPreviewLayer: AVCaptureVideoPreviewLayer?
    private var currentCameraDevice: AVCaptureDevice?
    private var currentCameraInput: AVCaptureDeviceInput?
    
    // 当前配置
    private var currentPosition: AVCaptureDevice.Position = .back
    private var currentFlashMode: AVCaptureDevice.FlashMode = .off
    private var isInitialized = false
    private var _isSessionPaused = false
    
    // 回调
    public typealias InitializationCallback = (Bool, String?) -> Void
    public typealias CaptureCallback = (String?, Int64, String?) -> Void
    
    private var initializationCallback: InitializationCallback?
    private var captureCallback: CaptureCallback?
    
    // MARK: - Public Methods
    
    /**
     * 检查摄像头是否可用
     */
    public func isAvailable() -> Bool {
        let authStatus = AVCaptureDevice.authorizationStatus(for: .video)
        print("NativeCameraManager: isAvailable() 检查权限状态: \(authStatus.rawValue)")
        
        let discoverySession = AVCaptureDevice.DiscoverySession(
            deviceTypes: [.builtInWideAngleCamera],
            mediaType: .video,
            position: .unspecified
        )
        let devices = discoverySession.devices
        print("NativeCameraManager: 发现摄像头设备数量: \(devices.count)")
        
        for (index, device) in devices.enumerated() {
            print("NativeCameraManager: 设备 \(index): \(device.localizedName), 位置: \(device.position.rawValue)")
        }
        
        let isAuthorized = authStatus == .authorized
        let hasDevices = !devices.isEmpty
        
        print("NativeCameraManager: 权限已授权: \(isAuthorized)")
        print("NativeCameraManager: 有可用设备: \(hasDevices)")
        
        let result = isAuthorized && hasDevices
        print("NativeCameraManager: isAvailable() 结果: \(result)")
        
        return result
    }
    
    /**
     * 初始化摄像头
     */
    public func initialize(position: AVCaptureDevice.Position = .back, callback: @escaping InitializationCallback) {
        print("NativeCameraManager: initialize调用 - 当前状态: isInitialized=\(isInitialized)")
        
        // 如果已经初始化且位置相同，直接返回成功
        if isInitialized && currentPosition == position {
            print("NativeCameraManager: 已初始化且位置相同，直接返回成功")
            callback(true, nil)
            return
        }
        
        // 如果已经初始化但位置不同，需要重新配置
        if isInitialized && currentPosition != position {
            print("NativeCameraManager: 位置改变，重新配置摄像头")
            currentPosition = position
            setupCamera()
            callback(true, nil)
            return
        }
        
        // 首次初始化
        print("NativeCameraManager: 首次初始化摄像头")
        self.initializationCallback = callback
        self.currentPosition = position
        
        // 检查权限
        checkCameraPermission { [weak self] granted in
            if granted {
                self?.setupCamera()
            } else {
                callback(false, "缺少摄像头权限")
            }
        }
    }
    
    /**
     * 拍照
     */
    public func takePicture(callback: @escaping CaptureCallback) {
        guard let photoOutput = self.photoOutput else {
            callback(nil, 0, "摄像头未初始化")
            return
        }
        
        self.captureCallback = callback
        
        let settings = AVCapturePhotoSettings()
        settings.flashMode = currentFlashMode
        
        // 设置图片格式
        if photoOutput.availablePhotoCodecTypes.contains(.jpeg) {
            if #available(iOS 13.0, *) {
                // 确保不超过最大支持的质量优先级
                let maxPriority = photoOutput.maxPhotoQualityPrioritization
                if maxPriority.rawValue >= AVCapturePhotoOutput.QualityPrioritization.quality.rawValue {
                    settings.photoQualityPrioritization = .quality
                } else {
                    settings.photoQualityPrioritization = maxPriority
                }
            }
        }
        
        photoOutput.capturePhoto(with: settings, delegate: self)
    }
    
    /**
     * 切换摄像头
     */
    public func switchCamera(callback: @escaping (Bool, String?) -> Void) {
        guard let session = captureSession else {
            callback(false, "摄像头未初始化")
            return
        }
        
        let newPosition: AVCaptureDevice.Position = (currentPosition == .back) ? .front : .back
        
        guard let newCamera = getCameraDevice(for: newPosition) else {
            callback(false, "未找到指定方向的摄像头")
            return
        }
        
        do {
            let newInput = try AVCaptureDeviceInput(device: newCamera)
            
            session.beginConfiguration()
            
            // 移除旧输入
            if let currentInput = currentCameraInput {
                session.removeInput(currentInput)
            }
            
            // 添加新输入
            if session.canAddInput(newInput) {
                session.addInput(newInput)
                currentCameraInput = newInput
                currentCameraDevice = newCamera
                currentPosition = newPosition
            } else {
                // 恢复旧输入
                if let currentInput = currentCameraInput {
                    session.addInput(currentInput)
                }
                callback(false, "无法添加新的摄像头输入")
                session.commitConfiguration()
                return
            }
            
            session.commitConfiguration()
            callback(true, nil)
            
        } catch {
            callback(false, "切换摄像头失败: \(error.localizedDescription)")
        }
    }
    
    /**
     * 设置闪光灯模式
     */
    public func setFlashMode(_ mode: AVCaptureDevice.FlashMode) {
        currentFlashMode = mode
        
        guard let device = currentCameraDevice, device.hasFlash else {
            return
        }
        
        // 对于iOS 10.0+，闪光灯模式通过AVCapturePhotoSettings设置
        // 这里只保存模式，实际设置在拍照时进行
    }
    
    /**
     * 获取预览层
     */
    public func getPreviewLayer() -> AVCaptureVideoPreviewLayer? {
        print("NativeCameraManager: getPreviewLayer() 被调用")
        print("NativeCameraManager: videoPreviewLayer = \(videoPreviewLayer != nil ? "存在" : "nil")")
        print("NativeCameraManager: captureSession.isRunning = \(captureSession?.isRunning ?? false)")
        print("NativeCameraManager: isInitialized = \(isInitialized)")
        return videoPreviewLayer
    }
    
    /**
     * 检查是否有前置摄像头
     */
    public func hasFrontCamera() -> Bool {
        return getCameraDevice(for: .front) != nil
    }
    
    /**
     * 检查是否有后置摄像头
     */
    public func hasBackCamera() -> Bool {
        return getCameraDevice(for: .back) != nil
    }
    
    /**
     * 检查是否支持闪光灯
     */
    public func hasFlash() -> Bool {
        return currentCameraDevice?.hasFlash ?? false
    }
    
    /**
     * 释放资源
     */
    public func dispose() {
        captureSession?.stopRunning()
        captureSession = nil
        photoOutput = nil
        videoPreviewLayer = nil
        currentCameraDevice = nil
        currentCameraInput = nil
        isInitialized = false
        _isSessionPaused = false
    }

    /**
     * 暂停摄像头session
     * 在iOS中，通过停止AVCaptureSession来实现session暂停
     */
    public func pauseSession() {
        guard let session = captureSession, isInitialized, !_isSessionPaused else {
            return
        }
        
        print("NativeCameraManager: 暂停摄像头session")
        DispatchQueue.global(qos: .userInitiated).async {
            session.stopRunning()
            DispatchQueue.main.async {
                self._isSessionPaused = true
                print("NativeCameraManager: 摄像头session已暂停")
            }
        }
    }

    /**
     * 恢复摄像头session
     * 在iOS中，通过重新启动AVCaptureSession来实现session恢复
     */
    public func resumeSession() {
        guard let session = captureSession, isInitialized, _isSessionPaused else {
            return
        }
        
        print("NativeCameraManager: 恢复摄像头session")
        DispatchQueue.global(qos: .userInitiated).async {
            session.startRunning()
            DispatchQueue.main.async {
                self._isSessionPaused = false
                print("NativeCameraManager: 摄像头session已恢复")
            }
        }
    }

    /**
     * 检查session是否已暂停
     */
    public func isSessionPaused() -> Bool {
        return _isSessionPaused
    }
    
    // MARK: - Private Methods
    
    private func checkCameraPermission(completion: @escaping (Bool) -> Void) {
        let status = AVCaptureDevice.authorizationStatus(for: .video)
        print("NativeCameraManager: 检查摄像头权限状态: \(status.rawValue)")
        
        switch status {
        case .authorized:
            print("NativeCameraManager: 摄像头权限已授权")
            completion(true)
        case .notDetermined:
            print("NativeCameraManager: 请求摄像头权限")
            AVCaptureDevice.requestAccess(for: .video) { granted in
                DispatchQueue.main.async {
                    print("NativeCameraManager: 摄像头权限请求结果: \(granted)")
                    completion(granted)
                }
            }
        case .denied, .restricted:
            print("NativeCameraManager: 摄像头权限被拒绝或受限")
            completion(false)
        @unknown default:
            print("NativeCameraManager: 未知的摄像头权限状态")
            completion(false)
        }
    }
    
    private func setupCamera() {
        print("NativeCameraManager: 开始设置摄像头，当前方向: \(currentPosition.rawValue)")
        
        guard let camera = getCameraDevice(for: currentPosition) else {
            let errorMsg = "未找到指定方向的摄像头"
            print("NativeCameraManager: 错误 - \(errorMsg)")
            initializationCallback?(false, errorMsg)
            return
        }
        
        print("NativeCameraManager: 找到摄像头设备: \(camera.localizedName)")
        
        do {
            // 创建会话
            let session = AVCaptureSession()
            session.sessionPreset = .photo
            
            // 创建输入
            let input = try AVCaptureDeviceInput(device: camera)
            if session.canAddInput(input) {
                session.addInput(input)
                currentCameraInput = input
                currentCameraDevice = camera
            } else {
                initializationCallback?(false, "无法添加摄像头输入")
                return
            }
            
            // 创建照片输出
            let photoOutput = AVCapturePhotoOutput()
            if session.canAddOutput(photoOutput) {
                session.addOutput(photoOutput)
                self.photoOutput = photoOutput
            } else {
                initializationCallback?(false, "无法添加照片输出")
                return
            }
            
            // 创建预览层
            let previewLayer = AVCaptureVideoPreviewLayer(session: session)
            previewLayer.videoGravity = .resizeAspectFill
            self.videoPreviewLayer = previewLayer
            
            self.captureSession = session
            
            // 启动会话
            print("NativeCameraManager: 启动摄像头会话")
            DispatchQueue.global(qos: .userInitiated).async {
                session.startRunning()
                DispatchQueue.main.async {
                    print("NativeCameraManager: 摄像头会话启动完成")
                    self.isInitialized = true
                    self.initializationCallback?(true, nil)
                    
                    // 发送摄像头初始化完成通知
                    NotificationCenter.default.post(
                        name: NSNotification.Name("CameraInitialized"),
                        object: self
                    )
                }
            }
            
        } catch {
            initializationCallback?(false, "初始化摄像头失败: \(error.localizedDescription)")
        }
    }
    
    private func getCameraDevice(for position: AVCaptureDevice.Position) -> AVCaptureDevice? {
        let discoverySession = AVCaptureDevice.DiscoverySession(
            deviceTypes: [.builtInWideAngleCamera],
            mediaType: .video,
            position: position
        )
        return discoverySession.devices.first
    }
    
    private func getDocumentsDirectory() -> URL {
        let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
        guard !paths.isEmpty else {
            // 如果无法获取文档目录，返回临时目录
            return FileManager.default.temporaryDirectory
        }
        return paths[0]
    }
}

// MARK: - AVCapturePhotoCaptureDelegate

extension NativeCameraManager: AVCapturePhotoCaptureDelegate {
    public func photoOutput(_ output: AVCapturePhotoOutput, didFinishProcessingPhoto photo: AVCapturePhoto, error: Error?) {
        if let error = error {
            captureCallback?(nil, 0, "拍照失败: \(error.localizedDescription)")
            return
        }
        
        guard let imageData = photo.fileDataRepresentation() else {
            captureCallback?(nil, 0, "无法获取图片数据")
            return
        }
        
        // 保存图片到文档目录
        let filename = "photo_\(Int(Date().timeIntervalSince1970 * 1000)).jpg"
        let documentsPath = getDocumentsDirectory()
        let multiCameraPath = documentsPath.appendingPathComponent("multi_camera", isDirectory: true)
        
        // 创建目录
        try? FileManager.default.createDirectory(at: multiCameraPath, withIntermediateDirectories: true, attributes: nil)
        
        let fileURL = multiCameraPath.appendingPathComponent(filename)
        
        do {
            try imageData.write(to: fileURL)
            let fileSize = Int64(imageData.count)
            captureCallback?(fileURL.path, fileSize, nil)
        } catch {
            captureCallback?(nil, 0, "保存图片失败: \(error.localizedDescription)")
        }
    }
}
